package com.atguigu.education.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.education.bean.TestPaperQuestionBean;
import com.atguigu.education.util.ClickHouseUtil;
import com.atguigu.education.util.DateFormatUtil;
import com.atguigu.education.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsTestQuestionWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // TODO 2 配置状态后端
        /*
           env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
           env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
           env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
           env.setStateBackend(new HashMapStateBackend());
           env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
           System.setProperty("HADOOP_USER_NAME", "atguigu");
        */
        // TODO 3 从Kafka主题中读取数据
        String topicName = "topic_db";
        String groupID = "dws_test_question_window";
        DataStreamSource<String> dbStream = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupID));
        // TODO 4 过滤出所需答题数据转化为json
        SingleOutputStreamOperator<JSONObject> jsonObjStream = dbStream.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
                    String table = jsonObject.getString("table");
                    String type = jsonObject.getString("type");
                    JSONObject data = jsonObject.getJSONObject("data");
                    if ("test_exam_question".equals(table) && "insert".equals(type)) {
                        out.collect(data);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        // TODO 5 转换为格式为bean
        SingleOutputStreamOperator<TestPaperQuestionBean> beanStream =
                jsonObjStream.flatMap(new FlatMapFunction<JSONObject, TestPaperQuestionBean>() {
                    @Override
                    public void flatMap(JSONObject value, Collector<TestPaperQuestionBean> out) throws Exception {
                        String questionId = value.getString("question_id");
                        Long isCorrect = value.getLong("is_correct");
                        Long ts = DateFormatUtil.toTs(value.getString("create_time"), true);
                        if( isCorrect == 1){
                            out.collect(new TestPaperQuestionBean("","",questionId,1L,1L,ts) );
                        } else {
                            out.collect(new TestPaperQuestionBean("","",questionId,1L,0L,ts) );
                        }
                    }
                });
        // TODO 6 设置水位线
        SingleOutputStreamOperator<TestPaperQuestionBean> beanWithWatermarkStream = beanStream
                .assignTimestampsAndWatermarks(WatermarkStrategy.<TestPaperQuestionBean>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                        .withTimestampAssigner(new SerializableTimestampAssigner<TestPaperQuestionBean>() {
                            @Override
                            public long extractTimestamp(TestPaperQuestionBean element, long recordTimestamp) {
                                return element.getTs();
                            }
                        }));
        // TODO 7 按问题id分组
        KeyedStream<TestPaperQuestionBean, String> keyedStream = beanWithWatermarkStream.keyBy(new KeySelector<TestPaperQuestionBean, String>() {
            @Override
            public String getKey(TestPaperQuestionBean value) throws Exception {
                return value.getQuestionId();
            }
        });
        // TODO 8 开窗聚合
        SingleOutputStreamOperator<TestPaperQuestionBean> reducedStream =
                keyedStream.window(TumblingEventTimeWindows.of(Time.seconds(10L)))
                        .reduce(new ReduceFunction<TestPaperQuestionBean>() {
                            @Override
                            public TestPaperQuestionBean reduce(TestPaperQuestionBean value1, TestPaperQuestionBean value2) throws Exception {
                                value1.setCount(value1.getCount() + value2.getCount());
                                value1.setRightCount(value1.getRightCount() + value2.getRightCount());
                                return value1;
                            }
                        }, new WindowFunction<TestPaperQuestionBean, TestPaperQuestionBean, String, TimeWindow>() {
                            @Override
                            public void apply(String s, TimeWindow window, Iterable<TestPaperQuestionBean> input, Collector<TestPaperQuestionBean> out) throws Exception {
                                TestPaperQuestionBean testPaperQuestionBean = input.iterator().next();
                                testPaperQuestionBean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                                testPaperQuestionBean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                                testPaperQuestionBean.setTs(System.currentTimeMillis());
                                out.collect(testPaperQuestionBean);
                            }
                        });

        // TODO 9 写入clickhouse
        reducedStream.addSink(ClickHouseUtil.getClickHouseSinkFunc("insert into dws_test_question_window values" +
                "(?,?,?,?,?,?"));

        // TODO 10 执行
        env.execute(groupID);
    }
}
